package com.itheima.ydd.common;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${ydd.path}")
    String basePath;

    @PostMapping("/upload")
    public ResultData upload(MultipartFile file) {

        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //获取后缀名
        String suffix = null;
        if (originalFilename != null) {
            int index = originalFilename.lastIndexOf(".");
            suffix = originalFilename.substring(index);
        }

        //生成保存在本地的文件名
        String fileName = UUID.randomUUID().toString() + suffix;
        //String fileName = IdWorker.getIdStr() + suffix;
        System.out.println("fileName = " + fileName);

        //获取文件件
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        //转存到本地
        try {
            file.transferTo(new File(dir + "/" + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String, Object> data = new HashMap<>();
        data.put("savePath", "/" + fileName);
        data.put("name", originalFilename);
        data.put("mime", file.getContentType());
        data.put("size", file.getSize());
        return ResultData.ok("",data);

    }
    //文件下载
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}